<template>
  <t-drawer
    v-model:visible="formVisible"
    size="medium"
    size-draggable
    :footer="false"
    :header="isEdit ? '编辑' : '新增'"
  >
    <div>
      <t-form ref="formRef" :data="form" :rules="rules" @submit="onSubmit">
        <t-form-item name="name" label="机构名称">
          <t-input v-model="form.name" placeholder="请填写机构名称" />
        </t-form-item>
        <t-form-item name="code" label="机构编码">
          <t-input v-model="form.code" placeholder="请填写机构编码" />
        </t-form-item>
        <t-form-item name="type" label="机构类型">
          <t-select v-model="form.type" :options="ORG_TYPES" placeholder="请选择机构类型"></t-select>
        </t-form-item>
        <t-form-item name="parentId" label="上级机构">
          <t-tree-select
            v-model="form.parentId"
            :keys="{
              label: 'name',
              value: 'id',
            }"
            :data="renderData"
            clearable
            placeholder="请选择上级机构"
          ></t-tree-select>
        </t-form-item>
        <t-form-item name="sort" label="排序">
          <t-input v-model="form.sort" />
        </t-form-item>
        <t-form-item name="phone" label="电话">
          <t-input v-model="form.phone" placeholder="请填写电话" />
        </t-form-item>
        <t-form-item name="address" label="地址">
          <t-input v-model="form.address" placeholder="请填写地址" />
        </t-form-item>
        <t-form-item name="remarks" label="备注">
          <t-input v-model="form.remarks" />
        </t-form-item>
        <t-form-item>
          <t-button variant="outline" @click="close">取消</t-button>
          <t-button theme="primary" type="submit">确定</t-button>
        </t-form-item>
      </t-form>
    </div>
  </t-drawer>
</template>

<script lang="ts" setup>
import { MessagePlugin, SubmitContext } from 'tdesign-vue-next';
import { computed, ref } from 'vue';
import { useRequest } from 'vue-request';

import { addOrg, getOrgTree, updateOrg } from '@/api/upms/org';
import { ORG_TYPES } from '@/constants';
import { useVisible } from '@/hooks/visible';

const { data } = useRequest(getOrgTree);

const renderData = computed(() => data.value || []);

const formRef = ref();

const initData = () => {
  return {
    id: '',
    name: '',
    code: '',
    type: '',
    parentId: '',
    phone: '',
    remarks: '',
    address: '',
    sort: '',
  };
};

const rules = {
  name: [
    {
      required: true,
      message: '机构名不能为空',
    },
  ],
  code: [
    {
      required: true,
      message: '机构编码不能为空',
    },
  ],
  parentId: [
    {
      required: true,
      message: '上级组织机构不能为空',
    },
  ],
  type: [
    {
      required: true,
      message: '机构类型不能为空',
    },
  ],
};

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  formData: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const emit = defineEmits<{
  (e: 'update:visible', v: boolean): void;
  (e: 'refresh'): void;
}>();

const form = ref(props.formData);

const { formVisible, close, open } = useVisible(props, emit);

// 判断是编辑还是新增
const isEdit = computed(() => !!form.value.id);

const onSubmit = async (ctx: SubmitContext) => {
  if (ctx.validateResult === true) {
    if (isEdit.value) {
      await updateOrg(form.value).then(() => {
        MessagePlugin.success('修改成功');
      });
    } else {
      await addOrg(form.value).then(() => {
        MessagePlugin.success('添加成功');
      });
    }
    form.value = { ...initData };
    formVisible.value = false;
    emit('refresh');
  } else {
    MessagePlugin.warning(ctx.firstError);
  }
};

open(() => {
  const { id } = props.formData;
  if (id) {
    form.value = props.formData;
  } else {
    form.value = initData();
  }
});
</script>
